// 主线程代码
import { task_wait } from "@/api/xhs";

const maxWorkers = 5; // 最大线程数
const activeWorkers = []; // 当前活跃的 Worker

export const republishTask = async () => {
  // 从 localStorage 中获取数据
  const user = localStorage.getItem("user")
    ? JSON.parse(localStorage.getItem("user"))
    : undefined;
  const pythons = localStorage.getItem("pythons")
    ? JSON.parse(localStorage.getItem("pythons"))
    : {};
  const exact_key = navigator.userAgent.indexOf("Win") !== -1 ? "_win" : "";
  try {
    const wait_data = await task_wait();
    if (wait_data.code === 0) {
      const { tasks } = wait_data.data;
      if (!tasks) return;

      for (let i = 0; i < tasks.length; i++) {
        const task = tasks[i];
        const { ads_powers } = task;
        console.log("activeWorkers", activeWorkers);
        // 等待直到有可用的 Worker 线程
        while (activeWorkers.length >= maxWorkers) {
          await new Promise((resolve) => setTimeout(resolve, 100)); // 等待 100ms 后重试
        }

        // 创建 Web Worker
        const worker = new Worker(`/republishTaskWorker.js?t=${Date.now()}`);
        activeWorkers.push(worker); // 将新 Worker 加入活跃列表

        // 向 Worker 发送数据
        worker.postMessage({
          type: "req",
          task,
          ads_powers,
          user,
          pythons,
          exact_key,
        });

        // 监听 Worker 的返回结果
        worker.addEventListener("message", async (event) => {
          if (event.data.type === "fetch") {
            const { url, options } = event.data;
            const response = await window.electronAPI.fetch(url, options);
            console.log("response", response, event.data);
            worker.postMessage({ type: "fetchResponse", response });
          } else if (event.data.type === "downloadAndExecute") {
            const { options } = event.data;
            console.log("downloadAndExecute", event.data);
            const response = await window.electronAPI.downloadAndExecute(
              options.downloadUrl,
              options.args,
              options.filename
            );
            worker.postMessage({
              type: "downloadAndExecuteResponse",
              response,
            });
          } else if (event.data.status === "done") {
            console.log("所有任务执行完成", event.data);
            worker.terminate(); // 所有任务完成后关闭 Worker
            const index = activeWorkers.indexOf(worker);
            if (index !== -1) {
              activeWorkers.splice(index, 1); // 从活跃列表中移除 Worker
            }
          }
        });

        // 监听 Worker 的错误
        worker.addEventListener("error", (error) => {
          console.error("Worker 错误:", error);
          worker.terminate(); // 关闭 Worker
          const index = activeWorkers.indexOf(worker);
          if (index !== -1) {
            activeWorkers.splice(index, 1); // 从活跃列表中移除 Worker
          }
        });
      }
    }
  } catch (err) {
    console.log(err);
  }
};
